package com.hpc.Controller;

import Utils.JSONUtil;
import Utils.ResultUtil;
import com.hpc.VO.fileUploadVo;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;
import java.net.URL;
import java.util.UUID;

@RestController
@RequestMapping("/ts/article/api")
public class commonController {
    @Value("${baseUrl}")
    public String baseUrl;
    public static final String prefixUrlOfArticle="http://localhost:8081/ts/article/articleImages/";
    public static final String prefixUrlOfCover="http://localhost:8081/ts/article/covers/";
    @GetMapping("/getImage")
    public String getImage(String fileName){
        String imagesDirPath = "/bishe/TS/images/";
        File file = new File(imagesDirPath + fileName);

        if (!file.exists()) {
            return JSONUtil.toJSONString(ResultUtil.error("图片文件不存在"));
        }

        byte[] bytes;
        try {
            bytes = org.apache.commons.io.FileUtils.readFileToByteArray(file);
        } catch (IOException e) {
            return JSONUtil.toJSONString(ResultUtil.error("图片获取失败！"));
        }

        return JSONUtil.toJSONString(ResultUtil.success(bytes));
    }
    @PostMapping("/imageUpload")
    public String changeheadsculpture(@RequestParam("file") MultipartFile file,@RequestParam(required = false) String type) throws IOException {
//        String token = request.getHeader("token");
//        String userid = JWTUtil.decodejwt(token).getClaim("userid").asString();
        System.out.println(type);
        boolean isCover=false;//是否为封面上传
//        if(type.equals("cover")){
//            return JSONUtil.toJSONString(fileUploadVo.success("http://localhost:8081/ts/user/HeadSculpture/user-b51d9284221b49d18595c5c609e13300.jpg"));
//        }
        if(!StringUtils.isEmpty(type) && type.equals("cover")){
            isCover=true;
        }
        // 生成新的文件名
        String uuid = UUID.randomUUID().toString().replaceAll("-", "");
        String extension = getFileExtension(file.getOriginalFilename());
        String fileName="";
        if(isCover){
            fileName = "cover-" + uuid + "."+extension;
            baseUrl="/covers/";

        }else{
            fileName = "article-" + uuid + "."+extension;
            baseUrl="/articleImages/";
        }
        //将图片保存在项目路径下的static下的articleImage文件夹下
        //获取当前项目静态资源目录
        // 获取当前类的ClassLoader
        ClassLoader classLoader = getClass().getClassLoader();

        // 获取resources/static目录的URL
        URL resourceUrl = classLoader.getResource("static");
        String articleImagesDirPath = "";
        if (resourceUrl != null) {
            // 获取绝对路径
            String absolutePath = new File(resourceUrl.getFile()).getAbsolutePath();
            System.out.println("Static resources directory: " + absolutePath);
            articleImagesDirPath = absolutePath + baseUrl;
        } else {
            System.out.println("Static resources directory not found.");
        }
        //获取当前年份，按年份分割文件夹
        String year = String.valueOf(java.time.LocalDate.now().getYear());
        // 拼接文件路径
        String filePath = articleImagesDirPath+year;
            //如果不存在则创建该文件夹
            File fileDir = new File(filePath);
            if (!fileDir.exists()) {
                fileDir.mkdirs();
            }
            // 保存文件
            file.transferTo(new File(filePath, fileName));
            // 返回可直接访问的文件名
            String imageUrl=(isCover?prefixUrlOfCover:prefixUrlOfArticle)+year+"/"+fileName;
        return JSONUtil.toJSONString(fileUploadVo.success(imageUrl));
    }
    private String getFileExtension(String filename) {
        int lastDotIndex = filename.lastIndexOf('.');
        if (lastDotIndex == -1) {
            return "";
        }
        return filename.substring(lastDotIndex + 1);
    }
}
